﻿using System;
using System.Diagnostics;
using System.ServiceModel;
using ShellCommandClientService.PushShellCommandServiceReference;
using ShellCommandClientService.ShellCommandResultLoggerServiceReference;

namespace ShellCommandClientService
{
    class MyCallBack : IPushShellCommandCallback, IDisposable
    {
        private PushShellCommandClient proxy;
        private ShellCommandResultLoggerClient loggerProxyClient;
        private IShellCommandExecuter shellCommandExecuter;
        public MyCallBack(IShellCommandExecuter commandExecuter)
        {
            this.shellCommandExecuter = commandExecuter;
        }

        public void CallBackFunction(ShellCommandInfo shellCommandInfo)
        {
            //Process cmd = new Process();
            string result = string.Empty;
            bool isShellCommnadRunSuccess = false;
            
            result = shellCommandExecuter.Execute(shellCommandInfo,out isShellCommnadRunSuccess);
            if (loggerProxyClient == null)
            {
                loggerProxyClient = new ShellCommandResultLoggerClient();
            }
            ShellCommandResult shellCommandResult = new ShellCommandResult()
            {
                MachineName = shellCommandInfo.MachineName,
                Result = result,
                ExecutionTime = DateTime.Now,
                Command = shellCommandInfo.Text
            };
            if (isShellCommnadRunSuccess)
            {
                shellCommandResult.Type = ResultType.Success;
            }
            else
            {
                shellCommandResult.Type = ResultType.Exception;
            }
            loggerProxyClient.LogResult(shellCommandResult);
            if (proxy != null)
            {
                proxy.Close();
            }
            if (loggerProxyClient == null)
            {
                loggerProxyClient.Close();
            }
        }

        public void callService()
        {
            InstanceContext context = new InstanceContext(this);
            proxy = new PushShellCommandClient(context);
            proxy.NormalFunction(System.Environment.MachineName);
        }

        public void Dispose()
        {
            proxy.Close();
        }

    }
}
